package com.example.my.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.my.entity.Permission;
import com.example.my.service.PermissionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    private final PermissionService permissionService;

    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }


    @GetMapping("/page")
    public IPage<Permission> page(@RequestParam(defaultValue = "1") long current,
                                  @RequestParam(defaultValue = "10") long size) {
        return permissionService.getPermissionsByPage(new Page<>(current, size));
    }


    @GetMapping("/page/search")
    public IPage<Permission> searchPage(@RequestParam(defaultValue = "1") long current,
                                        @RequestParam(defaultValue = "10") long size,
                                        @RequestParam(required = false) String keyword) {
        return permissionService.getPermissionsByPageWithCondition(new Page<>(current, size), keyword);
    }


    @PostMapping("/create")
    public boolean create(@RequestBody Permission permission) {
        // 防重：权限名称或 key 已存在则返回 false
        if (permissionService.count(new QueryWrapper<Permission>()
                .eq("perm_name", permission.getPermName())) > 0) {
            return false;
        }
        if (permissionService.count(new QueryWrapper<Permission>()
                .eq("perm_key", permission.getPermKey())) > 0) {
            return false;
        }
        return permissionService.save(permission);
    }


    @PostMapping("/delete/ids")
    public boolean delete(@RequestBody List<Long> ids) {
        return permissionService.removeByIds(ids);
    }

}